package database

import (
	"database/sql"
	"time"

	_ "modernc.org/sqlite"
)

var DB *sql.DB

func Init(dbPath string) error {
	var err error
	DB, err = sql.Open("sqlite", dbPath)
	if err != nil {
		return err
	}

	if err := DB.Ping(); err != nil {
		return err
	}

	return createTables()
}

func Close() error {
	if DB != nil {
		return DB.Close()
	}
	return nil
}

func createTables() error {
	schema := `
	CREATE TABLE IF NOT EXISTS users (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		username TEXT UNIQUE NOT NULL,
		password_hash TEXT NOT NULL,
		space_enabled BOOLEAN DEFAULT 0,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP
	);

	CREATE TABLE IF NOT EXISTS models (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		user_id INTEGER NOT NULL,
		name TEXT NOT NULL,
		description TEXT,
		file_data BLOB,
		file_format TEXT DEFAULT 'GLB',
		job_id TEXT,
		status TEXT DEFAULT 'completed',
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
	);

	CREATE TABLE IF NOT EXISTS comments (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		model_id INTEGER NOT NULL,
		user_id INTEGER NOT NULL,
		content TEXT NOT NULL,
		is_voice BOOLEAN DEFAULT 0,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		FOREIGN KEY (model_id) REFERENCES models(id) ON DELETE CASCADE,
		FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
	);

	CREATE INDEX IF NOT EXISTS idx_models_user ON models(user_id);
	CREATE INDEX IF NOT EXISTS idx_comments_model ON comments(model_id);
	`

	_, err := DB.Exec(schema)
	return err
}

// User 模型
type User struct {
	ID           int64
	Username     string
	PasswordHash string
	SpaceEnabled bool
	CreatedAt    time.Time
}

// Model 模型
type Model struct {
	ID          int64
	UserID      int64
	Name        string
	Description string
	FileData    []byte
	FileFormat  string
	JobID       string
	Status      string // generating, completed, failed
	CreatedAt   time.Time
}

// Comment 留言
type Comment struct {
	ID        int64
	ModelID   int64
	UserID    int64
	Content   string
	IsVoice   bool
	CreatedAt time.Time
}
